import {
  FC,
  ReactNode,
  ReactElement,
  useMemo,
  MouseEvent,
  CSSProperties,
  useCallback
} from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import {
  Layout,
  Nav,
  Button,
  Avatar,
  BackTop,
  Tooltip,
  Breadcrumb,
  Dropdown,
  Modal,
} from '@douyinfe/semi-ui';
import {
  IconSemiLogo,
  IconBell,
  /* IconHelpCircle, */
  IconUser,
  IconSun,
  IconMoon,
} from '@douyinfe/semi-icons';
import type { MenuRouteObject } from '@/types/router';
import * as tokenUtils from '@/utils/token';
import { NavItems } from '@douyinfe/semi-ui/lib/es/navigation';

import './index.scss';
import { LoginUser } from '@/types/store';

const { Header, /* Footer, */ Sider, Content } = Layout;

interface IProps {
  showSider: boolean;
  showAvatar: boolean;
  pageRoutes: MenuRouteObject[];
  itemKeys: string[];
  theme: 'light' | 'dark';
  toggleTheme: () => void;
  children: ReactNode;
  showMessageBtn: boolean;
  loginUser: Partial<LoginUser>;
  onMessageBtnClick: (e: MouseEvent) => void | Promise<void>;
  breadcurmbList: string[];
  contentStyle: CSSProperties;
}

export const AdminLayout: FC<Partial<IProps>> = ({
  showSider = true,
  pageRoutes = [],
  itemKeys = [],
  children,
  showMessageBtn = true,
  onMessageBtnClick,
  theme,
  toggleTheme,
  breadcurmbList,
  contentStyle = {},
  showAvatar = true,
  loginUser,
}): ReactElement => {
  const routeNavigate = useNavigate();

  const routeNavItems: NavItems = useMemo(() => {
    return formatPageRoutesToNavItem(pageRoutes?.[0]?.children ?? []);

    function formatPageRoutesToNavItem(pageRoutes: MenuRouteObject[]) {
      const target: NavItems = pageRoutes
        .filter(item => item.hide !== true)
        .map((item: MenuRouteObject) => {
          return {
            itemKey: item.fullpath ?? item.path,
            text: item.title,
            icon: item.icon,
            isSubNav: item?.children?.length > 0,
            items: item.children
              ? formatPageRoutesToNavItem(item.children)
              : undefined,
          };
        });
      return target;
    }
  }, [pageRoutes]);

  const handleLogout = useCallback(() => {
    Modal.warning({
      title: '提示',
      content: '确定要退出登录吗？',
      onOk: () => {
        tokenUtils.removeToken();
        routeNavigate('/common/login');
      }
    });
  }, [routeNavigate]);

  console.log('loginUser -> ', loginUser);

  return (
    <Layout
      className="page-container-layout"
      style={{ border: '1px solid var(--semi-color-border)' }}
    >
      <Header className="page-layout-header">
        <div>
          <Nav mode="horizontal" defaultSelectedKeys={['Home']}>
            <Nav.Header>
              <IconSemiLogo
                style={{ height: '36px', fontSize: 36, cursor: 'pointer' }}
                onClick={() => routeNavigate('/')}
              />
            </Nav.Header>
            <span style={{ color: 'var(--semi-color-text-2)' }}>
              <span
                style={{
                  marginRight: '24px',
                  color: 'var(--semi-color-text-0)',
                  fontWeight: '600',
                }}
              >
                一线通 - 管理后台
              </span>
            </span>
            <Nav.Footer>
              <Tooltip content={`切換为${theme === 'light' ? '浅色' : '深色'}主题`}>
                <Button
                  theme="borderless"
                  icon={theme === 'light' ? <IconMoon size="large" /> : <IconSun size="large" />}
                  style={{
                    color: 'var(--semi-color-text-2)',
                    marginRight: '12px',
                  }}
                  onClick={toggleTheme}
                />
              </Tooltip>
              {showMessageBtn && (
                <Tooltip content="查看站内通知">
                  <Button
                    theme="borderless"
                    icon={<IconBell size="large" />}
                    style={{
                      color: 'var(--semi-color-text-2)',
                      marginRight: '12px',
                    }}
                    onClick={onMessageBtnClick}
                  />
                </Tooltip>
              )}
              {/* <Button
                theme="borderless"
                icon={<IconHelpCircle size="large" />}
                style={{
                  color: 'var(--semi-color-text-2)',
                  marginRight: '12px',
                }}
              /> */}
              {showAvatar && (
                <Dropdown
                  render={(
                    <Dropdown.Menu>
                      <Dropdown.Item onClick={handleLogout}>退出登录</Dropdown.Item>
                    </Dropdown.Menu>
                  )}
                  trigger="click"
                >
                  <div style={{ cursor: 'pointer', border: '1px solid transparent', boxSizing: 'border-box' }}>
                    <Avatar
                      color="orange"
                      size="small"
                      src={loginUser.avatar}
                    >
                      {!loginUser.avatar && <IconUser />}
                    </Avatar>
                    <span style={{ marginLeft: '8px' }}>
                      {loginUser.username}
                    </span>
                  </div>
                </Dropdown>
              )}
            </Nav.Footer>
          </Nav>
        </div>
      </Header>
      <Layout>
        {showSider && (
          <Sider
            style={{
              backgroundColor: 'var(--semi-color-bg-1)',
              maxWidth: 300,
              // height: '100%',
            }}
          >
            <Nav
              style={{ maxWidth: 220, height: '100%' }}
              bodyStyle={{ maxHeight: 800 }}
              selectedKeys={itemKeys}
              items={routeNavItems}
              // onClick={(data) => typeof data.itemKey === 'string' && routeNavigate(data.itemKey)}
              onSelect={(item) => typeof item.itemKey === 'string' && routeNavigate(item.itemKey)}
              footer={{
                collapseButton: true,
              }}
            />
          </Sider>
        )}
        <Content
          className="layout-inner-content"
          style={{
            display: 'flex',
            flexDirection: 'column',
            minHeight: '100vh',
            padding: '15px 15px 60px',
            boxSizing: 'border-box',
            backgroundColor: 'var(--semi-color-bg-0)',
            ...contentStyle,
          }}
        >
          <div style={{ marginBottom: 15 }}>
            {breadcurmbList?.length > 0 && (
              <Breadcrumb routes={breadcurmbList} />
            )}
          </div>
          {children}
          <Outlet />
        </Content>
        <BackTop
          style={{
            height: 30,
            width: 30,
            borderRadius: '100%',
            backgroundColor: '#0077fa',
            textAlign: 'center',
            color: '#fff',
            bottom: 100,
          }}
          visibilityHeight={1}
        // target={() => document.querySelector('.container-full') ?? window}
        />
        {/* <Footer
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            padding: '20px',
            color: 'var(--semi-color-text-2)',
            backgroundColor: 'rgba(var(--semi-grey-0), 1)',
          }}
        >
          <span
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
          ></span>
        </Footer> */}
      </Layout>
    </Layout>
  );
}
